package org.alfresco.demo.transform.pdf;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

import javax.imageio.ImageIO;

import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.transform.AbstractContentTransformer;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.util.TempFileProvider;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

/**
 * 
 * @author rui.fernandes@alfresco.com
 * 
 */
@SuppressWarnings("deprecation")
public class PDFBoxOnlyImageTransformer extends AbstractContentTransformer {

	@Override
	protected void transformInternal(ContentReader reader,
			ContentWriter writer, Map<String, Object> options) throws Exception {
		String formatName = getImageType(writer);
		InputStream is = reader.getContentInputStream();
		PDDocument document = PDDocument.load(is);
		try {
			PDPage page = (PDPage) document.getDocumentCatalog().getAllPages()
					.get(0);
			BufferedImage image = page.convertToImage();
			File tempFile = TempFileProvider.createTempFile(
					"PDFBoxOnlyImageTransformer-" + System.currentTimeMillis(),
					formatName);
			ImageIO.write(image, formatName, tempFile);
			writer.putContent(tempFile);
		} finally {
			if (document != null)
				try {
					document.close();
				} catch (Throwable e) {
				}
			if (is != null)
				try {
					is.close();
				} catch (Throwable e) {
				}
		}

	}

	private static String getImageType(ContentWriter writer) {
		if (writer.getMimetype().equals(MimetypeMap.MIMETYPE_IMAGE_JPEG))
			return "jpg";
		else if (writer.getMimetype().equals(MimetypeMap.MIMETYPE_IMAGE_PNG))
			return "png";
		else if (writer.getMimetype().equals(MimetypeMap.MIMETYPE_IMAGE_GIF))
			return "gif";
		else
			return null;
	}

	@Override
	protected double getReliability(String sourceMimetype, String targetMimetype) {
		return MimetypeMap.MIMETYPE_PDF.equals(sourceMimetype)
				&& (MimetypeMap.MIMETYPE_IMAGE_JPEG.equals(targetMimetype)
						|| MimetypeMap.MIMETYPE_IMAGE_GIF
								.equals(targetMimetype) || MimetypeMap.MIMETYPE_IMAGE_PNG
							.equals(targetMimetype)) ? 1 : 0;
	}
}
